package hh.util.bean.codegen;

import hh.compile.CompileUtil;
import hh.util.StringUtil;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author huanghuai
 * @date 2020/10/27
 */
public class JavaBeanCreatorFactory {
    static final AtomicInteger index = new AtomicInteger(0);

    static final String pkg = "hh.util.beanutil.codegen";
    static final String classNamePrefix = "CGNew";
    static final String creatorCode = "package " + pkg + ";" +
            "public final class ? implements " + JavaBeanCreator.class.getName() + "{" +
            "@Override public Object newObject(){return new ?();}" +
            "}";

    public static JavaBeanCreator getObject(Class clazz) {
        String className = classNamePrefix + index.getAndIncrement();
        String fullClassName = pkg + "." + className;
        String sourceCode = StringUtil.formatQ(creatorCode, className, clazz.getName());
        try {
            return (JavaBeanCreator) CompileUtil.compile(fullClassName, sourceCode).newInstance();
        } catch (Exception e) {
            throw new IllegalArgumentException(e);
        }
    }
}
